import datetime

from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse

# Create your views here.

from leave.models import LeaveLog


def test(request):
    return HttpResponse('hello')


def add_leave(request):
    """
    请假

    :param request:
    :return:
    """
    classname = request.GET.get('classname')
    name = request.GET.get('name')
    phone = request.GET.get('phone')
    go_place = request.GET.get('go_place')
    description = request.GET.get('description')
    try:
        LeaveLog.objects.create(
            classname=classname,
            name=name,
            phone=phone,
            go_place=go_place,
            description=description
        )
        return JsonResponse({'code': 1, 'msg': '提交成功'}, safe=False)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'提交失败:{e}'}, safe=False)


def returned(request):
    """
    销假

    :param request:
    :return:
    """
    try:
        id = request.GET.get('id')
        log = LeaveLog.objects.get(id=id)
        log.status = 2
        log.return_time = datetime.datetime.now()
        log.save()
        return JsonResponse({'code': 1, 'msg': '提交成功'}, safe=False)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'提交失败:{e}'}, safe=False)


def query(request):
    """
    通过手机号码查询请假情况

    :param request:
    :return:
    """
    phone = request.GET.get('phone')
    datas = LeaveLog.objects.filter(phone=phone).order_by('-create_time')
    data = [{
        'id': i.id,
        'classname': i.classname,
        'name': i.name,
        'phone': i.phone,
        'go_place': i.go_place,
        'description': i.description,
        'status': i.status,
        'rejection': i.rejection,
        'create_time': i.create_time,
        'return_time': i.return_time
    } for i in datas]
    return JsonResponse(data, safe=False)
